<template>
  <div class="upload uploadWechat">
    <i></i>
    <input type="file" class="pointer" accept="image/jpeg,image/jpg,image/png" @change="change($event)" name='file'>
    <div v-show="isloading" class="uploading">{{$t('personal.uploadIn')}}...</div>
    <div v-show="showImg" class="showImg"><img :src="showImg" alt="上传的图片"></div>
  </div>
</template>

<script>
  export default {
    name: 'upload',
    props: {
      showImg: {
        type: String,
        default: null
      }
    },
    data () {
      return {
        isloading: false
      }
    },
    methods: {
      change (e) {
        let self = this
        self.files = e.target.files[0] || e.dataTransfer.files[0]
        if (this.files && this.files.size <= 10 * 1024 * 1024) { // 判断大小
          let reader = new FileReader()
          reader.readAsDataURL(self.files)
          reader.onload = function (e) {
            self.upload(this.result)
            self.isloading = true
            self.$store.dispatch('setTipState', self.$t('personal.uploadIn'))
          }
        } else {
          this.$store.dispatch('setTipState', {text: this.$t('personal.placeholder_12'), type: 'error'})
        }
      },
      upload (file) {
        if (file) {
          let formData = new FormData()
          formData.append(this.name, this.files)
          if (this.data !== undefined) {
            for (let key in this.data)formData.append(key, this.data[key])
          }
          let isOpenUploadImg = this.$store.state.baseData._data.is_open_upload_img || '0'
          this.axios({
            headers: {
              'Content-Type': 'multipart/form-data' // application/json
            },
            method: 'post',
            url: this.$store.state.url.common.upload_img,
            hostType: (isOpenUploadImg === '1') ? 'upload' : null,
            params: formData
          }).then((result) => {
            if (result.code === '0') {
              this.isloading = false
              this.$emit('onevents', {value: result.data})
              this.$store.dispatch('setTipState', this.$t('personal.uploadCuccess'))
            } else {
              this.isloading = false
              this.$store.dispatch('setTipState', {text: this.$t('error.' + result.code), type: 'error'})
            }
          }).catch(() => {
            this.isloading = false
          })
        }
      }
    }
  }
</script>
